<?php
	require('trade.doc.php');
	$app->post(
		'/trade/add',
		function() use($app, $db2){
			$data = $app->request()->post();
			try{
				$db2->beginTransaction();
				$echo['error'] = "";
				if($data && isset($data['payway']) && isset($data['userid']) && isset($data['usertype'])){
					if(empty($data['orderid']) && empty($data['rechargenum'])){
						$echo['error'] = "不允许交易";
						echo json_encode($echo);exit;
					}
					$userid=$data['userid'];
					$usertype=$data['usertype'];
					$orderid=$data['orderid'];
					$paystate=1;
					$pwd=$data['pwd'];
					$payway=$data['payway'];
					//判断orderid是否存在
					if(!empty($orderid)){
						$orderids=explode(',',$orderid);
						$ordernum=count($orderids);
						for($i=0;$i<$ordernum;$i++){
							//获取流水号及订单信息
							if($payway!=0 && $payway!=3){
								$trade[$i]=$db2->select(1,"tb_trade","tradeid",array('orderid'=>$orderids[$i],'type'=>1)); //充值记录
							}else{
								$trade[$i]=$db2->select(1,"tb_trade","tradeid",array('orderid'=>$orderids[$i],'type'=>0)); //下单记录
							}
							$order[$i]=$db2->select(1,"tb_order",array("userid","usertype","tbid","price"),array("idcode"=>$orderids[$i],"state"=>1));
							$trademoney[$i]=$order[$i]['price'];
							if(empty($order[$i]['tbid']) || $order[$i]['userid']!=$userid){
								$paystate=0;
							}
						}
					}
					$rechargeid='';
					if($ordernum!=0){
						for($n=0;$n<$ordernum;$n++){
							if($paystate==1){
								$sqlwhere=array();
								if($payway==0 || empty($orderid)){
									$sqlwhere['paypassword']=$pwd;
								}
								$sqlwhere['tbid']=$userid;
								$tb = $usertype == 1 ? 'tb_member' : 'tb_coach';
								$user=$db2->select(1,$tb,"*",$sqlwhere);
								if($payway==0 || $payway==3){
									if(empty($user['tbid']) && $payway==0){
										$echo['error'] = "支付密码错误";
										echo json_encode($echo);exit;
									}else{
										$lack=false;
										/*if($payway==0){
											if($trademoney[$n]>$user['balance']){
												$lack=true;
											}
										}elseif($payway==3){*/
										    $discount = 1;
											$ordertype=$db2->select(3,"tb_order","type",array('idcode'=>$orderid));
											if($usertype==1 && $db2->select(2, 'tb_member', '*', array('tbid' => $userid,'#date_format(privilege_dt,"%Y-%m-%d")[>]'=>'curdate()'))==1){
												$discount=0.8;
												$db2->update('tb_order',array('isprivilege'=>1,'discount'=>$discount),array('idcode'=>$orderid));
											}
											if($usertype==2){
												$level=$db2->select(3, 'tb_coach', 'level',array('tbid'=>$userid));
												switch($level){
													case 0: $discount=1;break;
													case 1: $discount=1;break;
													case 2: $discount=0.95;break;
													case 3: $discount=0.9;break;
													default: $discount=1;break;
												}
												$db2->update('tb_order',array('level'=>$level,'discount'=>$discount,'pumped'=>$pumped),array('idcode'=>$orderid));
											}
											if($ordertype!=2 && $ordertype!=5){
												$trademoney[$n]=$trademoney[$n]*$discount;
											}
											if($user['adaa']<$trademoney[$n]/2 && $trademoney[$n]>$user['balance']+$user['adaa']){
												$lack=true;
											}elseif($user['adaa']>=$trademoney[$n]/2 && $trademoney[$n]/2>$user['balance']){
												$lack=true;
											}
										/*}*/
										if($lack==true){
											$echo['error'] = "用户余额不足";
											echo json_encode($echo);exit;
										}
									}
								}elseif(empty($user['tbid'])){
									$echo['error'] = "用户数据错误";
									echo json_encode($echo);exit;
								}
							}
							if(empty($trade[$n]['tradeid'])){
								//没有充值订单号的订单
								$tradeid=getordernum("TR");
								$rechargeid.=$tradeid.",";
								if($paystate==1){	
									if($payway!=0 && $payway!=3 && $paystate==1){
										$pay=array('type'=>1,'userid'=>$userid,'usertype'=>$usertype,'trademoney'=>$trademoney[$n],'payway'=>$payway,'order'=>$orderids[$n],'tradeid'=>$tradeid);
										creattrade($pay);
									}							//支付方式不为余额支付，那么所有的其他支付方式先充值，后付款
									if(!empty($orderid)){
										$tradeid2=getordernum("TR");
										
										if(($payway==3 || $payway==0) && $user['adaa']>0){
											if($user['adaa']<$trademoney[$n]/2){
												$adaa=$user['adaa'];
											}elseif($user['adaa']>=$trademoney[$n]/2){
												$adaa=$trademoney[$n]/2;
											}
											$trademoney[$n]-=$adaa;
											$adaaid=getordernum("AD");
											$pay=array('type'=>2,'userid'=>$userid,'usertype'=>$usertype,'tradeadaa'=>$adaa,'order'=>$orderids[$n],'adaaid'=>$adaaid);
											$echo['adaa']=$adaa;
											creatadaa($pay);
										}
										
										$pay=array('type'=>0,'userid'=>$userid,'usertype'=>$usertype,'trademoney'=>$trademoney[$n],'order'=>$orderids[$n],'tradeid'=>$tradeid2);
										creattrade($pay);/*
										if($payway!=3){
											if(!updategoodsstock($orderids[$n])){
												$echo['error'] = "宝贝库存不足";
												exit(json_encode($echo));
											}
										}*/
									}
								}
							}else{
								//有充值订单号的订单
								$rechargeid.=$trade[$n]['tradeid'].",";
							}
						}
					}else{
						$tradeid=getordernum("TR");
						$rechargeid.=$tradeid.",";
						$trademoney[0]=$_POST['rechargenum'];
						$pay=array('type'=>1,'userid'=>$userid,'usertype'=>$usertype,'trademoney'=>$trademoney[0],'payway'=>$payway,'order'=>'','tradeid'=>$tradeid);
						creattrade($pay);
					}
					$rechargeid=substr($rechargeid,0,strlen($rechargeid)-1);
					$echo['rechargeid']=$rechargeid;
					$allmoney=0;
					foreach($trademoney as $value){
						$allmoney+=$value;
					}
					if($payway==0){
						//余额支付扣款
						foreach($orderids as $ordervalue){
							$tradeid=$db2->select(3,'tb_trade','tradeid',array('orderid'=>$ordervalue,'type'=>0));
							$adaaid=$db2->select(3,'tb_adaa','adaaid',array('orderid'=>$ordervalue,'type'=>2));
							if(!empty($tradeid)){
								if(checktrade($tradeid,0)==1 && checkorder($tradeid,1,0)==1){
									if(!updatetrade($tradeid,0,0) || ($adaaid && !updateadaa($adaaid,2))){
										$echo['error'] = "支付失败，请联系客服";
										echo json_encode($echo);exit;
									}
								}else{
									$echo['error'] = "订单记录不存在";
									echo json_encode($echo);exit;
								}
							}else{
								$echo['error'] = "交易记录不存在";
								echo json_encode($echo);exit;
							}
						}
					}else if($payway==3){
						//商品扣款
						foreach($orderids as $ordervalue){
							$tradeid=$db2->select(3,'tb_trade','tradeid',array('orderid'=>$ordervalue,'type'=>0));
							$adaaid=$db2->select(3,'tb_adaa','adaaid',array('orderid'=>$ordervalue,'type'=>2));
							if(!empty($tradeid)){
								if(checktrade($tradeid,0)==1 && checkorder($tradeid,1,0)==1){
									if(!updatetrade($tradeid,3,8) || ($adaaid && !updateadaa($adaaid,2))){
										$echo['error'] = "支付失败，请联系客服";
										echo json_encode($echo);exit;
									}
								}else{
									$echo['error'] = "订单记录不存在";
									echo json_encode($echo);exit;
								}
							}else{
								$echo['error'] = "交易记录不存在";
								echo json_encode($echo);exit;
							}
						}
					}else if($payway==4){
						//货到付款
						foreach($orderids as $ordervalue){
							$tradeid=$db2->select(3,'tb_trade','tradeid',array('orderid'=>$ordervalue,'type'=>0));
							if(!empty($tradeid)){
								if(checktrade($tradeid,0)==1 && checkorder($tradeid,1,0)==1){
									if(!updatetrade($tradeid,4,9)){
										$echo['error'] = "支付失败，请联系客服";
										echo json_encode($echo);exit;
									}
								}else{
									$echo['error'] = "订单记录不存在";
									echo json_encode($echo);exit;
								}
							}else{
								$echo['error'] = "交易记录不存在";
								echo json_encode($echo);exit;
							}
						}
					}
					if($paystate!=1){
						$echo['error'] = "支付数据有误，请检查";
					}
				}else{
					$echo['error'] = "数据缺失，请检查";
				}
				$db2->commit();
			}catch(Exception $e){
				$db2->catche($e);
				exit;
			}
			echo json_encode($echo);
		}
	);
	$app->get(
		'/trade/get',
		function() use($app, $db2){
			$data = $app->request()->get();
			$echo['error'] = "";
			if($data && isset($data['userid']) && isset($data['usertype'])  && isset($data['from']) && isset($data['to'])){
				$tb = $data['usertype'] == 1 ? 'tb_member' : 'tb_coach';
				$member=$db2->select(1, $tb, '*', array('tbid' => $data['userid']));
				if(!empty($member['tbid'])){
					$sqlwhere=array('userid' => $data['userid'],'order'=>'tbid desc');
					$echo['count'] = $db2->select(2, 'tb_tradedetail', '*', $sqlwhere);
					$sqlwhere['limit'] = array($data['from'], $data['to']);
					$trade=$db2->select(0, 'tb_tradedetail', '*', $sqlwhere);
					foreach($trade as $value){
						if($value['type']==0){
							$order=$db2->select(1,'tb_order','*',array('idcode'=>$db2->select(3,'tb_trade','orderid',array('tradeid'=>$value['tradeid']))));
							if($order['type']==1){
								$curriculum=$db2->select(1,'tb_curriculum_snap','*',array('idcode'=>$order['idcode']));
								$tmp['content']='购买 '.$curriculum['title'].' 课程 '.$curriculum['number'].'节 成功';
							}else if($order['type']==2){
								$tmp['content']='购买 特权 成功';
							}else if($order['type']==3){
								$place=$db2->select(1,'tb_place_snap','*',array('idcode'=>$order['idcode']));
								$tmp['content']='购买 场地 '.$place['name'].' 成功';
							}else if($order['type']==4){
								$place_curriculum=$db2->select(1,'tb_place_curriculum_snap','*',array('idcode'=>$order['idcode']));
								$tmp['content']='购买 '.$place_curriculum['title'].' 场地课程 成功';
							}
						}else if($value['type']==1){
							$tmp['content']='充值 成功';
						}else if($value['type']==2){
							$tmp['content']='退款 成功';
						}else if($value['type']==3){
							$tmp['content']='提现 成功';
						}else if($value['type']==4){
							$tmp['content']='取消提现 成功';
						}else if($value['type']==5){
							$order=$db2->select(1,'tb_order','*',array('idcode'=>$db2->select(3,'tb_trade','orderid',array('tradeid'=>$value['tradeid']))));
							if($order['type']==1){
								$curriculum=$db2->select(1,'tb_curriculum_snap','*',array('idcode'=>$order['idcode']));
								$tmp['content']='会员购买 '.$curriculum['title'].' 课程 '.$curriculum['number'].'节 成功';
							}else if($order['type']==4){
								$place_curriculum=$db2->select(1,'tb_place_curriculum_snap','*',array('idcode'=>$order['idcode']));
								$tmp['content']='会员购买 '.$place_curriculum['title'].' 场地课程 成功';
							}else if($order['type'] == 6){
							    $group_curriculum = $db2->select(1,'tb_group_curriculum_snap','*',array('idcode'=>$order['idcode']));
							    $tmp['content']='会员购买 '.$group_curriculum['title'].' 团体课程 成功';
							}
						}else if($value['type']==8){
							$tmp['content']='购买商品支付 成功';
						}else if($value['type']==6){
							$tmp['content']='退款拒绝';
						}
						$tmp['dt']=date('Y-m-d',strtotime($value['creatdate']));
						$tmp['time']=date('H:i',strtotime($value['creatdate']));
						$tmp['trademoney']=$value['trademoney'];
						$week=date('w',strtotime($value['creatdate']));
						switch($week){
							case 0:$week='日';break;
							case 1:$week='一';break;
							case 2:$week='二';break;
							case 3:$week='三';break;
							case 4:$week='四';break;
							case 5:$week='五';break;
							case 6:$week='六';break;
						}
						$tmp['week']='星期'.$week;
						$echo['data'][]=$tmp;
					}
				}else{
					$echo['error'] = "用户不存在";
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	$app->get(
	   '/trade/detail',
		function() use($app, $db2){
			$data = $app->request()->get();
			$echo['error'] = "";
			if($data && isset($data['userid']) && isset($data['usertype'])  && isset($data['tradeid'])){
				$tb = $data['usertype'] == 1 ? 'tb_member' : 'tb_coach';
				$member=$db2->select(1, $tb, '*', array('tbid' => $data['userid']));
				if(!empty($member['tbid'])){
					$sqlwhere=array('tradeid' => $data['tradeid']);
					$detail = $db2->select(1, 'tb_trade', '*', $sqlwhere);
					if(!empty($trade['orderid'])){
						$detail['order']=$db2->select(1, 'tb_order', '*', array('idcode'=>$detail['orderid']));
					}
					$echo['data'] = $detail;
				}else{
					$echo['error'] = "用户不存在";
				}
			}else{
				$echo['error'] = "数据缺失，请检查";
			}
			echo json_encode($echo);
		}
	);
	
	
	$app->get(
	    '/trade/alipay/web/synchronize',
	    function() use($app, $db2){
	        $data = $app->request()->get();
	        $echo['error'] = "";
	        if($data){
				$param=$data;
	            require_once("api/alipay_mobile/config.php");
				require_once("api/alipay_mobile/wappay/service/AlipayTradeService.php");
				$alipaySevice = new AlipayTradeService($config); 
				$result = $alipaySevice->check($param);
				$paystate=1;
        	    if($result) {
        	        $out_trade_no	= $param['out_trade_no'];	    //获取订单号
        	        $total_fee		= $param['total_fee'];			//获取总价格
					$param['trade_status']='TRADE_FINISHED';
        	        if($param['trade_status']=='TRADE_FINISHED' || $param['trade_status']=='TRADE_SUCCESS') {
        	            $tradenumber=$out_trade_no;
        	            if(!empty($tradenumber)){
        	                try{
    	                        $set=array('tradeid'=>$tradenumber,'type'=>1,'state'=>0, 'payway'=>1);
    	                        $tradeinfo = $db2->select(1, 'tb_trade', '*', $set);
    	                        if($tradeinfo){
    	                            $set=array('balance[+]'=>$tradeinfo['trademoney']);
    	                            $db2->update('tb_member', $set, array('tbid'=>$tradeinfo['userid']));
    	                            $db2->update('tb_trade', array('state'=>1), array('tradeid'=>$tradenumber));
									$member=$db2->select(1,'tb_member','*',array('tbid' => $tradeinfo['userid']));
									$money=$member['balance'];
									$db2->insert("tb_tradedetail",array("tradeid"=>$tradenumber,"b_money"=>$money,"a_money"=>$money+$tradeinfo['trademoney'],"trademoney"=>$tradeinfo['trademoney'],'#creatdate'=>'now()','type'=>1,'userid'=>$tradeinfo['userid']));
    	                        }else{
    	                            $paystate=5;
    	                        }

        	                }catch(Exception $e){
        	                    $paystate=4;
        	                }
        	            }else{
        	                $paystate=6;
        	            }
        	        }else{
        	            //验证失败
        	            $paystate=3;
        	        }
        	    }else{
        	        $paystate=2;
        	    }
        	    //$this->db->insert('trade',array('test'=>json_encode($_POST),'tradenumber'=>$paystate));
        	    if($paystate==1){
        	        header("Location:http://".$_SERVER['HTTP_HOST']."/account.html");
        	    }else{
					echo  $paystate;exit;
        	        header('Location:http://'.$_SERVER['HTTP_HOST'].'/order.pay.fail.php');
        	    }
        	    exit;
	        }
	    }
	);
	
	$app->post(
	    '/trade/alipay/web/asynchronize',
	    function() use($app, $db2){
	        $data = $app->request()->post();
	        $echo['error'] = "";
	        if($data){
				$param=$data;
	            require_once("api/alipay_mobile/config.php");
				require_once("api/alipay_mobile/wappay/service/AlipayTradeService.php");
				$alipaySevice = new AlipayTradeService($config); 
				$result = $alipaySevice->check($param);
				$paystate=1;
        	    if($verify_result) {
        	        $out_trade_no	= $param['out_trade_no'];	    //获取订单号
        	        if($param['trade_status']=='TRADE_FINISHED' || $param['trade_status']=='TRADE_SUCCESS') {
        	            $tradenumber=$out_trade_no;
        	            if(!empty($tradenumber)){
        	                try{
    	                        $set=array('tradeid'=>$tradenumber,'type'=>1,'state'=>0, 'payway'=>1);
    	                        $tradeinfo = $db2->select(1, 'tb_trade', '*', $set);
    	                        if($tradeinfo){
    	                            $set=array('balance[+]'=>$tradeinfo['trademoney']);
    	                            $db2->update('tb_member', $set, array('tbid'=>$tradeinfo['userid']));
    	                            $db2->update('tb_trade', array('state'=>1), array('tradeid'=>$tradenumber));
									$member=$db2->select(1,'tb_member','*',array('tbid' => $tradeinfo['userid']));
									$money=$member['balance'];
									$db2->insert("tb_tradedetail",array("tradeid"=>$tradenumber,"b_money"=>$money,"a_money"=>$money+$tradeinfo['trademoney'],"trademoney"=>$tradeinfo['trademoney'],'#creatdate'=>'now()','type'=>1,'userid'=>$tradeinfo['userid']));
    	                        }else{
    	                            $paystate=5;
    	                        }

        	                }catch(Exception $e){
        	                    $paystate=4;
        	                }
        	            }else{
        	                $paystate=6;
        	            }
        	        }else{
        	            //验证失败
        	            $paystate=3;
        	        }
        	    }else{
        	        $paystate=2;
        	    }
        	    //$this->db->insert('trade',array('test'=>json_encode($_POST),'tradenumber'=>$paystate));
        	    if($paystate==1){
        	        echo "success";
        	    }else{
        	        echo "fail";
        	    }
        	    exit;
	        }
	    }
	);
	
	$app->post(
	    '/trade/wechat/web/asynchronize',
	    function() use($app, $db2){
	        $data = $app->request()->post();
	        $echo['error'] = "";
	        
	        $xml = file_get_contents('php://input');
	        $xml_tree = new DOMDocument();
	        $xml_tree->loadXML($xml);
	        $paystate=1;
	        
	        if($xml_tree->getElementsByTagName('return_code')->item(0)->nodeValue=='SUCCESS'){
	            if(wx_checksign($xml_tree)){
	                if($xml_tree->getElementsByTagName('result_code')->item(0)->nodeValue=='SUCCESS'){
	                    $tradenumber	= $xml_tree->getElementsByTagName('out_trade_no')->item(0)->nodeValue;	    //获取订单号
	                    try{
	                            $set=array('tradeid'=>$tradenumber,'type'=>1,'state'=>0, 'payway'=>2);
    	                        $tradeinfo = $db2->select(1, 'tb_trade', '*', $set);
    	                        if($tradeinfo){
    	                            $set=array('balance[+]'=>$tradeinfo['trademoney']);
    	                            $db2->update('tb_member', $set, array('tbid'=>$tradeinfo['userid']));
    	                            $db2->update('tb_trade', array('state'=>1), array('tradeid'=>$tradenumber));
									$member=$db2->select(1,'tb_member','*',array('tbid' => $tradeinfo['userid']));
									$money=$member['balance'];
									$db2->insert("tb_tradedetail",array("tradeid"=>$tradenumber,"b_money"=>$money,"a_money"=>$money+$tradeinfo['trademoney'],"trademoney"=>$tradeinfo['trademoney'],'#creatdate'=>'now()','type'=>1,'userid'=>$tradeinfo['userid']));
    	                        }else{
    	                            $paystate=6;
    	                        }
	                    }catch(Exception $e){
	                        $paystate=5;
	                    }
	                }else{
	                    $paystate=4;
	                }
	            }else{
	                $paystate=3;
	            }
	        }else{
	            $paystate=2;
	        }
	        if($paystate==1){
	            //header("Location: account.html");
	            echo "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
	        }else{
	            echo "<xml><return_code><![CDATA[FAIL]]></return_code></xml>";
	        }
	        
	        
	        echo json_encode($echo);
	    }
	);
	
	$app->post(
	    '/trade/gen_trade',
	    function() use($app, $db2){
	        $data = $app->request()->post();
	        $echo['error'] = "";

	        if($data && isset($data['userid']) && isset($data['payway'])  && isset($data['money'])){
	           $tradenum = getordernum("TR");
	           
	           $set = array(
	               'tradeid' => $tradenum,
	               'creatdate' => date("Y-m-d H:i:s", time()),
	               'trademoney' => $data['money'],
	               'type' => 1,
	               'state' => 0,
	               'tradedate' => date("Y-m-d H:i:s", time()),
	               'userid' => $data['userid'],
	               'usertype' => 1,
	               'payway' => $data['payway']
	           );
	           $db2->insert('tb_trade', $set);
	           $echo['issuccess'] = 1;
	           $echo['trade_number'] = $tradenum;
	           echo json_encode($echo);
	        }
	    }
	);
	
	
	$app->get(
	    '/trade/pay/alipay',
	    function() use($app, $db2){
	        $data = $app->request()->get();
	        $echo['error'] = "";
	        if($data && isset($data['userid']) && isset($data['trade_number'])){
	            
	            $tmp = $db2->select(1, 'tb_trade', 'trademoney', array('tradeid'=>$data['trade_number'], 'type'=>1, 'state'=>0, 'payway'=>1));
	            if(!$tmp){
	                $data['error'] = "非法交易";
	                echo json_encode($data);
	                exit;
	            }
	            
	            require_once('api/alipay_mobile/alipay.class.php');
        	    $arr['payno'] = $data['trade_number'];
        	    $arr['subject'] = "充值";
        	    $arr['body'] = "充值";
        	    $arr['payment'] = $tmp['trademoney'];
        	    $arr['mode'] = 1;
        	    $obj = new payonline($arr);
        	    exit;
	        }
	    }
	);
	
	
	$app->get(
	    '/trade/pay/wxpay',
	    function() use($app, $db2){
	        $data = $app->request()->get();
	        $echo['error'] = "";
	
	        if($data && isset($data['userid']) && isset($data['trade_number'])){
	             
	            $tmp = $db2->select(1, 'tb_trade', 'trademoney', array('tradeid'=>$data['trade_number'], 'type'=>1, 'state'=>0, 'payway'=>2));
	            if(!$tmp){
	                $data1['error'] = "非法交易";
	                echo json_encode($data1);
	                exit;
	            }
	             
	            $param = array('title'=>'微信充值','tradenumber'=>$data['trade_number'],'total'=>$tmp['trademoney']);
				require_once('sqinc/inc/wxfunction.php');
	            $data=array_merge($data,unifiedorder($param));
	            echo json_encode($data);exit;
	            
	        }
	    }
	);
	
?>